package com.demo.download;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Download extends Thread {
	private String urlString = "";
	private String filename = "";
	private String savePath = "";

	private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
	public Download(String urlString, String filename, String savePath) {
		this.urlString = urlString;
		this.filename = filename;
		this.savePath = savePath;
	}


	@Override
	public void run() {
		// 构造URl
		try {
			URL url = new URL(urlString);
			// 打开连接
			URLConnection con = url.openConnection();
			con.addRequestProperty("User-Agent", "Mozilla/5.0 (iPhone; CPU iPhone OS 11_0 like Mac OS X) AppleWebKit/604.1.38 (KHTML, like Gecko) Version/11.0 Mobile/15A372 Safari/604.1");
			// 设置请求超时为5s
			con.setConnectTimeout(5 * 1000);
			// 输入流
			InputStream is = con.getInputStream();
			// 1K的数据缓冲
			byte[] bs = new byte[1024];
			// 读取到的数据长度
			int len;
			// 输出的文件流
			File sf = new File(savePath);
			if (!sf.exists()) {
				sf.mkdirs();
			}
			OutputStream os = new FileOutputStream(sf.getPath() + "\\" + filename);
			// 开始读取
			while ((len = is.read(bs)) != -1) {
				os.write(bs, 0, len);
			}
			// 完毕，关闭所有链接
			os.close();
			is.close();
			System.out.println(FORMAT.format(new Date()) + " ===> 图片 【" + filename + "】保存成功。");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
